home *** CD-ROM | disk | FTP | other *** search
/ TeX 1995 July / TeX CD-ROM July 1995 (Disc 1)(Walnut Creek)(1995).ISO / graphics / gnuplot / contour.c < prev    next >
C/C++ Source or Header  |  1993-09-15  |  43KB  |  1,285 lines

  1. #ifndef lint
  2. static char *RCSid = "$Id: contour.c%v 3.50 1993/07/09 05:35:24 woo Exp $";
  3. #endif
  4.  
  5.  
  6. /* GNUPLOT - contour.c */
  7. /*
  8.  * Copyright (C) 1986 - 1993   Thomas Williams, Colin Kelley
  9.  *
  10.  * Permission to use, copy, and distribute this software and its
  11.  * documentation for any purpose with or without fee is hereby granted, 
  12.  * provided that the above copyright notice appear in all copies and 
  13.  * that both that copyright notice and this permission notice appear 
  14.  * in supporting documentation.
  15.  *
  16.  * Permission to modify the software is granted, but not the right to
  17.  * distribute the modified code.  Modifications are to be distributed 
  18.  * as patches to released version.
  19.  *  
  20.  * This software is provided "as is" without express or implied warranty.
  21.  * 
  22.  *
  23.  * AUTHORS
  24.  * 
  25.  *   Original Software:
  26.  *       Gershon Elber
  27.  * 
  28.  * There is a mailing list for gnuplot users. Note, however, that the
  29.  * newsgroup 
  30.  *    comp.graphics.gnuplot 
  31.  * is identical to the mailing list (they
  32.  * both carry the same set of messages). We prefer that you read the
  33.  * messages through that newsgroup, to subscribing to the mailing list.
  34.  * (If you can read that newsgroup, and are already on the mailing list,
  35.  * please send a message info-gnuplot-request@dartmouth.edu, asking to be
  36.  * removed from the mailing list.)
  37.  *
  38.  * The address for mailing to list members is
  39.  *       info-gnuplot@dartmouth.edu
  40.  * and for mailing administrative requests is 
  41.  *       info-gnuplot-request@dartmouth.edu
  42.  * The mailing list for bug reports is 
  43.  *       bug-gnuplot@dartmouth.edu
  44.  * The list of those interested in beta-test versions is
  45.  *       info-gnuplot-beta@dartmouth.edu
  46.  */
  47.  
  48. #include <stdio.h>
  49. #include "plot.h"
  50.  
  51. #define DEFAULT_NUM_OF_ZLEVELS  10  /* Some dflt values (setable via flags). */
  52. #define DEFAULT_NUM_APPROX_PTS  5
  53. #define DEFAULT_BSPLINE_ORDER  3
  54. #define MAX_NUM_OF_ZLEVELS      100 /* Some max. values (setable via flags). */
  55. #define MAX_NUM_APPROX_PTS      100
  56. #define MAX_BSPLINE_ORDER      10
  57.  
  58. #define INTERP_NOTHING   0            /* Kind of interpolations on contours. */
  59. #define INTERP_CUBIC     1                           /* Cubic spline interp. */
  60. #define APPROX_BSPLINE   2                         /* Bspline interpolation. */
  61.  
  62. #define LEVELS_AUTO            0        /* How contour levels are set */
  63. #define LEVELS_INCREMENTAL    1        /* user specified start & incremnet */
  64. #define LEVELS_DISCRETE        2        /* user specified discrete levels */
  65. #define ACTIVE   1                    /* Status of edges at certain Z level. */
  66. #define INACTIVE 2
  67.  
  68. #define OPEN_CONTOUR     1                                 /* Contour kinds. */
  69. #define CLOSED_CONTOUR   2
  70.  
  71. #define EPSILON  1e-5              /* Used to decide if two float are equal. */
  72. #define INFINITY 1e10
  73.  
  74. #ifndef TRUE
  75. #define TRUE     -1
  76. #define FALSE    0
  77. #endif
  78.  
  79. #define DEFAULT_NUM_CONTOURS    10
  80. #define MAX_POINTS_PER_CNTR     100
  81. #define SHIFT_Z_EPSILON        0.000301060 /* Dec. change of poly bndry hit.*/
  82.  
  83. #define abs(x)  ((x) > 0 ? (x) : (-(x)))
  84. #define sqr(x)  ((x) * (x))
  85.  
  86. #ifndef AMIGA_AC_5
  87. extern double sqrt();
  88. #endif /* not AMIGA_AC_5 */
  89. typedef double tri_diag[3];         /* Used to allocate the tri-diag matrix. */
  90. typedef double table_entry[4];           /* Cubic spline interpolation 4 coef. */
  91.  
  92. struct vrtx_struct {
  93.     double X, Y, Z;                       /* The coordinates of this vertex. */
  94.     struct vrtx_struct *next;                             /* To chain lists. */
  95. };
  96.  
  97. struct edge_struct {
  98.     struct poly_struct *poly[2];   /* Each edge belongs to up to 2 polygons. */
  99.     struct vrtx_struct *vertex[2]; /* The two extreme points of this vertex. */
  100.     struct edge_struct *next;                             /* To chain lists. */
  101.     int status, /* Status flag to mark edges in scanning at certain Z level. */
  102.     boundary;                   /* True if this edge is on the boundary. */
  103. };
  104.  
  105. struct poly_struct {
  106.     struct edge_struct *edge[3];           /* As we do triangolation here... */
  107.     struct poly_struct *next;                             /* To chain lists. */
  108. };
  109.  
  110. struct cntr_struct {           /* Contours are saved using this struct list. */
  111.     double X, Y;                          /* The coordinates of this vertex. */
  112.     struct cntr_struct *next;                             /* To chain lists. */
  113. };
  114.  
  115. static int test_boundary;    /* If TRUE look for contours on boundary first. */
  116. static struct gnuplot_contours *contour_list = NULL;
  117. static double crnt_cntr[MAX_POINTS_PER_CNTR * 2];
  118. static int crnt_cntr_pt_index = 0;
  119. static double contour_level = 0.0;
  120. static table_entry *hermit_table = NULL;    /* Hold hermite table constants. */
  121. static int num_of_z_levels = DEFAULT_NUM_OF_ZLEVELS;  /* # Z contour levels. */
  122. static int num_approx_pts = DEFAULT_NUM_APPROX_PTS;/* # pts per approx/inter.*/
  123. static int bspline_order = DEFAULT_BSPLINE_ORDER;   /* Bspline order to use. */
  124. static int interp_kind = INTERP_NOTHING;  /* Linear, Cubic interp., Bspline. */
  125. static int levels_kind = LEVELS_AUTO;  /* auto, incremental, discrete */
  126.  
  127.  
  128. static void gen_contours();
  129. static int update_all_edges();
  130. static struct cntr_struct *gen_one_contour();
  131. static struct cntr_struct *trace_contour();
  132. static struct cntr_struct *update_cntr_pt();
  133. static int fuzzy_equal();
  134. static void gen_triangle();
  135. static struct vrtx_struct *gen_vertices();
  136. static struct edge_struct *gen_edges_middle();
  137. static struct edge_struct *gen_edges();
  138. static struct poly_struct *gen_polys();
  139. static void free_contour();
  140. static void put_contour();
  141. static put_contour_nothing();
  142. static put_contour_cubic();
  143. static put_contour_bspline();
  144. static calc_tangent();
  145. static int count_contour();
  146. static complete_spline_interp();
  147. static calc_hermit_table();
  148. static hermit_interp();
  149. static prepare_spline_interp();
  150. static int solve_tri_diag();
  151. static gen_bspline_approx();
  152. static double fetch_knot();
  153. static eval_bspline();
  154.  
  155. /*
  156.  * Entry routine to this whole set of contouring module.
  157.  */
  158. struct gnuplot_contours *contour(num_isolines, iso_lines,
  159.                  ZLevels, approx_pts, int_kind, order1,
  160.                  levels_kind, levels_list)
  161. int num_isolines;
  162. struct iso_curve *iso_lines;
  163. int ZLevels, approx_pts, int_kind, order1;
  164. int levels_kind;
  165. double *levels_list;
  166. {
  167.     int i;
  168.     struct poly_struct *p_polys, *p_poly;
  169.     struct edge_struct *p_edges, *p_edge;
  170.     struct vrtx_struct *p_vrts, *p_vrtx;
  171.     double x_min, y_min, z_min, x_max, y_max, z_max, z, dz;
  172.      struct gnuplot_contours *save_contour_list;
  173.  
  174.     num_of_z_levels = ZLevels;
  175.     num_approx_pts = approx_pts;
  176.     bspline_order = order1 - 1;
  177.     interp_kind = int_kind;
  178.  
  179.     contour_list = NULL;
  180.  
  181.     if (interp_kind == INTERP_CUBIC) calc_hermit_table();
  182.  
  183.     gen_triangle(num_isolines, iso_lines, &p_polys, &p_edges, &p_vrts,
  184.         &x_min, &y_min, &z_min, &x_max, &y_max, &z_max);
  185.     crnt_cntr_pt_index = 0;
  186.  
  187.     dz = (z_max - z_min) / (num_of_z_levels + 1);
  188.     z = z_min;
  189.     for (i = 0; i < num_of_z_levels; i++) {
  190.         switch(levels_kind) {
  191.             case LEVELS_AUTO:
  192.                 /* Step from z_min+dz upto z_max-dz in num_of_z_levels times. */
  193.                 z += dz;
  194.                 break;
  195.             case LEVELS_INCREMENTAL:
  196.                 z = levels_list[0] + i * levels_list[1];
  197.                 break;
  198.             case LEVELS_DISCRETE:
  199.                 z = levels_list[i];
  200.                 break;
  201.         }
  202.         contour_level = z;
  203.          save_contour_list = contour_list;
  204.         gen_contours(p_edges, z + dz * SHIFT_Z_EPSILON, x_min, x_max,
  205.                                 y_min, y_max);
  206.          if(contour_list != save_contour_list) {
  207.              contour_list->isNewLevel = 1;
  208.              sprintf(contour_list->label, "%8.3g", z);
  209.          }
  210.     }
  211.  
  212.     /* Free all contouring related temporary data. */
  213.     while (p_polys) {
  214.     p_poly = p_polys -> next;
  215.     free (p_polys);
  216.     p_polys = p_poly;
  217.     }
  218.     while (p_edges) {
  219.     p_edge = p_edges -> next;
  220.     free (p_edges);
  221.     p_edges = p_edge;
  222.     }
  223.     while (p_vrts) {
  224.     p_vrtx = p_vrts -> next;
  225.     free (p_vrts);
  226.     p_vrts = p_vrtx;
  227.     }
  228.  
  229.     if (interp_kind == INTERP_CUBIC) free(hermit_table);
  230.  
  231.     return contour_list;
  232. }
  233.  
  234. /*
  235.  * Adds another point to the currently build contour.
  236.  */
  237. add_cntr_point(x, y)
  238. double x, y;
  239. {
  240.     int index;
  241.  
  242.     if (crnt_cntr_pt_index >= MAX_POINTS_PER_CNTR-1) {
  243.     index = crnt_cntr_pt_index - 1;
  244.     end_crnt_cntr();
  245.     crnt_cntr[0] = crnt_cntr[index * 2];
  246.     crnt_cntr[1] = crnt_cntr[index * 2 + 1];
  247.     crnt_cntr_pt_index = 1; /* Keep the last point as first of this one. */
  248.     }
  249.     crnt_cntr[crnt_cntr_pt_index * 2] = x;
  250.     crnt_cntr[crnt_cntr_pt_index * 2 + 1] = y;
  251.     crnt_cntr_pt_index++;
  252. }
  253.  
  254. /*
  255.  * Done with current contour - create gnuplot data structure for it.
  256.  */
  257. end_crnt_cntr()
  258. {
  259.     int i;
  260.     struct gnuplot_contours *cntr = (struct gnuplot_contours *)
  261.                     alloc((unsigned long)sizeof(struct gnuplot_contours),
  262.                           "gnuplot_contour");
  263.  
  264.     cntr->coords = (struct coordinate GPHUGE *) gpfaralloc((unsigned long)sizeof(struct coordinate) *
  265.                               ( unsigned long)crnt_cntr_pt_index,
  266.                            "contour coords");
  267.     for (i=0; i<crnt_cntr_pt_index; i++) {
  268.     cntr->coords[i].x = crnt_cntr[i * 2];
  269.     cntr->coords[i].y = crnt_cntr[i * 2 + 1];
  270.     cntr->coords[i].z = contour_level;
  271.     }
  272.     cntr->num_pts = crnt_cntr_pt_index;
  273.  
  274.     cntr->next = contour_list;
  275.     contour_list = cntr;
  276.      contour_list->isNewLevel = 0;
  277.  
  278.     crnt_cntr_pt_index = 0;
  279. }
  280.  
  281. /*
  282.  * Generates all contours by tracing the intersecting triangles.
  283.  */
  284. static void gen_contours(p_edges, z_level, x_min, x_max, y_min, y_max)
  285. struct edge_struct *p_edges;
  286. double z_level, x_min, x_max, y_min, y_max;
  287. {
  288.     int num_active,                        /* Number of edges marked ACTIVE. */
  289.     contour_kind;                /* One of OPEN_CONTOUR, CLOSED_CONTOUR. */
  290.     struct cntr_struct *p_cntr;
  291.  
  292.     num_active = update_all_edges(p_edges, z_level);           /* Do pass 1. */
  293.  
  294.     test_boundary = TRUE;        /* Start to look for contour on boundaries. */
  295.  
  296.     while (num_active > 0) {                                   /* Do Pass 2. */
  297.         /* Generate One contour (and update MumActive as needed): */
  298.     p_cntr = gen_one_contour(p_edges, z_level, &contour_kind, &num_active);
  299.     put_contour(p_cntr, z_level, x_min, x_max, y_min, y_max,
  300.                   contour_kind); /* Emit it in requested format. */
  301.     }
  302. }
  303.  
  304. /*
  305.  * Does pass 1, or marks the edges which are active (crosses this z_level)
  306.  * as ACTIVE, and the others as INACTIVE:
  307.  * Returns number of active edges (marked ACTIVE).
  308.  */
  309. static int update_all_edges(p_edges, z_level)
  310. struct edge_struct *p_edges;
  311. double z_level;
  312. {
  313.     int count = 0;
  314.  
  315.     while (p_edges) {
  316.     if (((p_edges -> vertex[0] -> Z >= z_level) &&
  317.          (p_edges -> vertex[1] -> Z <= z_level)) ||
  318.         ((p_edges -> vertex[1] -> Z >= z_level) &&
  319.          (p_edges -> vertex[0] -> Z <= z_level))) {
  320.         p_edges -> status = ACTIVE;
  321.         count++;
  322.     }
  323.     else p_edges -> status = INACTIVE;
  324.     p_edges = p_edges -> next;
  325.     }
  326.  
  327.     return count;
  328. }
  329.  
  330. /*
  331.  * Does pass 2, or find one complete contour out of the triangolation data base:
  332.  * Returns a pointer to the contour (as linked list), contour_kind is set to
  333.  * one of OPEN_CONTOUR, CLOSED_CONTOUR, and num_active is updated.
  334.  */
  335. static struct cntr_struct *gen_one_contour(p_edges, z_level, contour_kind,
  336.                                 num_active)
  337. struct edge_struct *p_edges;
  338. double z_level;
  339. int *contour_kind, *num_active;
  340. {
  341.     struct edge_struct *pe_temp;
  342.  
  343.     if (test_boundary) {    /* Look for something to start with on boundary: */
  344.     pe_temp = p_edges;
  345.     while (pe_temp) {
  346.         if ((pe_temp -> status == ACTIVE) && (pe_temp -> boundary)) break;
  347.         pe_temp = pe_temp -> next;
  348.     }
  349.     if (!pe_temp) test_boundary = FALSE;/* No more contours on boundary. */
  350.     else {
  351.         *contour_kind = OPEN_CONTOUR;
  352.         return trace_contour(pe_temp, z_level, num_active, *contour_kind);
  353.     }
  354.     }
  355.  
  356.     if (!test_boundary) {        /* Look for something to start with inside: */
  357.     pe_temp = p_edges;
  358.     while (pe_temp) {
  359.         if ((pe_temp -> status == ACTIVE) && (!(pe_temp -> boundary)))
  360.         break;
  361.         pe_temp = pe_temp -> next;
  362.     }
  363.     if (!pe_temp) {
  364.         *num_active = 0;
  365.         return NULL;
  366.     }
  367.     else {
  368.         *contour_kind = CLOSED_CONTOUR;
  369.         return trace_contour(pe_temp, z_level, num_active, *contour_kind);
  370.     }
  371.     }
  372.     return NULL;             /* We should never be here, but lint... */
  373. }
  374.  
  375. /*
  376.  * Search the data base along a contour starts at the edge pe_start until
  377.  * a boundary edge is detected or until we close the loop back to pe_start.
  378.  * Returns a linked list of all the points on the contour
  379.  * Also decreases num_active by the number of points on contour.
  380.  */
  381. static struct cntr_struct *trace_contour(pe_start, z_level, num_active,
  382.                                 contour_kind)
  383. struct edge_struct *pe_start;
  384. double z_level;
  385. int *num_active, contour_kind;
  386. {
  387.     int i, in_middle;       /* If TRUE the z_level is in the middle of edge. */
  388.     struct cntr_struct *p_cntr, *pc_tail;
  389.     struct edge_struct *p_edge = pe_start, *p_next_edge;
  390.     struct poly_struct *p_poly, *PLastpoly = NULL;
  391.  
  392.     /* Generate the header of the contour - the point on pe_start. */
  393.     if (contour_kind == OPEN_CONTOUR) pe_start -> status = INACTIVE;
  394.     (*num_active)--;
  395.     p_cntr = pc_tail = update_cntr_pt(pe_start, z_level, &in_middle);
  396.     if (!in_middle) {
  397.     return NULL;
  398.     }
  399.  
  400.     do {
  401.     /* Find polygon to continue (Not where we came from - PLastpoly): */
  402.     if (p_edge -> poly[0] == PLastpoly) p_poly = p_edge -> poly[1];
  403.     else p_poly = p_edge -> poly[0];
  404.     p_next_edge = NULL;          /* In case of error, remains NULL. */
  405.     for (i=0; i<3; i++)              /* Test the 3 edges of the polygon: */
  406.         if (p_poly -> edge[i] != p_edge)
  407.             if (p_poly -> edge[i] -> status == ACTIVE)
  408.             p_next_edge = p_poly -> edge[i];
  409.     if (!p_next_edge) {
  410.         pc_tail -> next = NULL;
  411.         free_contour(p_cntr);
  412.         return NULL;
  413.     }
  414.     p_edge = p_next_edge;
  415.     PLastpoly = p_poly;
  416.     p_edge -> status = INACTIVE;
  417.     (*num_active)--;
  418.     pc_tail -> next = update_cntr_pt(p_edge, z_level, &in_middle);
  419.     if (!in_middle) {
  420.         pc_tail -> next = NULL;
  421.         free_contour(p_cntr);
  422.         return NULL;
  423.     }
  424.         pc_tail = pc_tail -> next;
  425.     }
  426.     while ((pe_start != p_edge) && (!p_edge -> boundary));
  427.     pc_tail -> next = NULL;
  428.  
  429.     return p_cntr;
  430. }
  431.  
  432. /*
  433.  * Allocates one contour location and update it to to correct position
  434.  * according to z_level and edge p_edge. if z_level is found to be at
  435.  * one of the extreme points nothing is allocated (NULL is returned)
  436.  * and in_middle is set to FALSE.
  437.  */
  438. static struct cntr_struct *update_cntr_pt(p_edge, z_level, in_middle)
  439. struct edge_struct *p_edge;
  440. double z_level;
  441. int *in_middle;
  442. {
  443.     double t;
  444.     struct cntr_struct *p_cntr;
  445.  
  446.     t = (z_level - p_edge -> vertex[0] -> Z) /
  447.     (p_edge -> vertex[1] -> Z - p_edge -> vertex[0] -> Z);
  448.  
  449.     if (fuzzy_equal(t, 1.0) || fuzzy_equal(t, 0.0)) {
  450.         *in_middle = FALSE;
  451.         return NULL;
  452.     }
  453.     else {
  454.     *in_middle = TRUE;
  455.     p_cntr = (struct cntr_struct *) alloc((unsigned long)sizeof(struct cntr_struct),
  456.                             "contour cntr_struct");
  457.     p_cntr -> X = p_edge -> vertex[1] -> X * t +
  458.              p_edge -> vertex[0] -> X * (1-t);
  459.     p_cntr -> Y = p_edge -> vertex[1] -> Y * t +
  460.              p_edge -> vertex[0] -> Y * (1-t);
  461.     return p_cntr;
  462.     }
  463. }
  464.  
  465. /*
  466.  * Simple routine to decide if two real values are equal by simply
  467.  * calculating the relative/absolute error between them (< EPSILON).
  468.  */
  469. static int fuzzy_equal(x, y)
  470. double x, y;
  471. {
  472.     if (abs(x) > EPSILON)            /* Calculate relative error: */
  473.         return (abs((x - y) / x) < EPSILON);
  474.     else                    /* Calculate absolute error: */
  475.     return (abs(x - y) < EPSILON);
  476. }
  477.  
  478. /*
  479.  * Generate the triangles.
  480.  * Returns the lists (vrtxs edges & polys) via pointers to their heads.
  481.  */
  482. static void gen_triangle(num_isolines, iso_lines, p_polys, p_edges,
  483.     p_vrts, x_min, y_min, z_min, x_max, y_max, z_max)
  484. int num_isolines;
  485. struct iso_curve *iso_lines;
  486. struct poly_struct **p_polys;
  487. struct edge_struct **p_edges;
  488. struct vrtx_struct **p_vrts;
  489. double *x_min, *y_min, *z_min, *x_max, *y_max, *z_max;
  490. {
  491.     int i, grid_x_max = iso_lines->p_count;
  492.     struct vrtx_struct *p_vrtx1, *p_vrtx2, *pv_temp;
  493.     struct edge_struct *p_edge1, *p_edge2, *pe_tail1, *pe_tail2, *pe_temp,
  494.               *p_edge_middle, *pe_m_tail;
  495.     struct poly_struct *p_poly, *pp_tail;
  496.  
  497.     *p_polys = NULL;
  498.     *p_edges = NULL;
  499.     *p_vrts = NULL;
  500.     *z_min = INFINITY;
  501.     *y_min = INFINITY;
  502.     *x_min = INFINITY;
  503.     *z_max = -INFINITY;
  504.     *y_max = -INFINITY;
  505.     *x_max = -INFINITY;
  506.  
  507.     /* Read 1st row. */
  508.     p_vrtx1 = gen_vertices(grid_x_max, iso_lines->points,
  509.                x_min, y_min, z_min, x_max, y_max, z_max);
  510.     *p_vrts = p_vrtx1;
  511.     /* Gen. its edges.*/
  512.     pe_temp = p_edge1 = gen_edges(grid_x_max, p_vrtx1, &pe_tail1);
  513.     for (i = 1; i < grid_x_max; i++) {/* Mark one side of edges as boundary. */
  514.     pe_temp -> poly[1] = NULL;
  515.     pe_temp = pe_temp -> next;
  516.     }
  517.     for (i = 1; i < num_isolines; i++) { /* Read next column and gen. polys. */
  518.     iso_lines = iso_lines->next;
  519.         /* Get row into list. */
  520.         p_vrtx2 = gen_vertices(grid_x_max, iso_lines->points,
  521.                    x_min, y_min, z_min, x_max, y_max, z_max);
  522.         /* Generate its edges. */
  523.         p_edge2 = gen_edges(grid_x_max, p_vrtx2, &pe_tail2);
  524.     /* Generate edges from one vertex list to the other one: */
  525.     p_edge_middle = gen_edges_middle(grid_x_max, p_vrtx1, p_vrtx2,
  526.                                  &pe_m_tail);
  527.  
  528.     /* Now we can generate the polygons themselves (triangles). */
  529.     p_poly = gen_polys(grid_x_max, p_edge1, p_edge_middle, p_edge2,
  530.                                  &pp_tail);
  531.         pe_tail1 -> next = (*p_edges);      /* Chain new edges to main list. */
  532.         pe_m_tail -> next = p_edge1;
  533.     *p_edges = p_edge_middle;
  534.     pe_tail1 = pe_tail2;
  535.     p_edge1 = p_edge2;
  536.  
  537.     pv_temp = p_vrtx2;
  538.     while (pv_temp -> next) pv_temp = pv_temp -> next;
  539.     pv_temp -> next = *p_vrts;
  540.     *p_vrts = p_vrtx1 = p_vrtx2;
  541.  
  542.         pp_tail -> next = (*p_polys);       /* Chain new polys to main list. */
  543.     *p_polys = p_poly;
  544.     }
  545.  
  546.     pe_temp = p_edge1;
  547.     for (i = 1; i < grid_x_max; i++) {/* Mark one side of edges as boundary. */
  548.     pe_temp -> poly[0] = NULL;
  549.     pe_temp = pe_temp -> next;
  550.     }
  551.  
  552.     pe_tail1 -> next = (*p_edges);    /* Chain last edges list to main list. */
  553.     *p_edges = p_edge1;
  554.  
  555.     /* Update the boundary flag, saved in each edge, and update indexes: */
  556.     pe_temp = (*p_edges);
  557.     i = 1;
  558.  
  559.     while (pe_temp) {
  560.     pe_temp -> boundary = (!(pe_temp -> poly[0])) ||
  561.                   (!(pe_temp -> poly[1]));
  562.     pe_temp = pe_temp -> next;
  563.     }
  564. }
  565.  
  566. /*
  567.  * Handles grid_x_max 3D points (One row) and generate linked list for them.
  568.  */
  569. static struct vrtx_struct *gen_vertices(grid_x_max, points,
  570.                       x_min, y_min, z_min, x_max, y_max, z_max)
  571. int grid_x_max;
  572. struct coordinate GPHUGE *points;
  573. double *x_min, *y_min, *z_min, *x_max, *y_max, *z_max;
  574. {
  575.     int i;
  576.     struct vrtx_struct *p_vrtx, *pv_tail, *pv_temp;
  577.  
  578.     for (i=0; i<grid_x_max; i++) {/* Get a point and generate the structure. */
  579.         pv_temp = (struct vrtx_struct *) alloc((unsigned long)sizeof(struct vrtx_struct),
  580.                         "contour vertex");
  581.     pv_temp -> X = points[i].x;
  582.     pv_temp -> Y = points[i].y;
  583.     pv_temp -> Z = points[i].z;
  584.  
  585.     if (pv_temp -> X > *x_max) *x_max = pv_temp -> X; /* Update min/max. */
  586.     if (pv_temp -> Y > *y_max) *y_max = pv_temp -> Y;
  587.     if (pv_temp -> Z > *z_max) *z_max = pv_temp -> Z;
  588.     if (pv_temp -> X < *x_min) *x_min = pv_temp -> X;
  589.     if (pv_temp -> Y < *y_min) *y_min = pv_temp -> Y;
  590.     if (pv_temp -> Z < *z_min) *z_min = pv_temp -> Z;
  591.  
  592.     if (i == 0)                              /* First vertex in row: */
  593.         p_vrtx = pv_tail = pv_temp;
  594.     else {
  595.         pv_tail -> next = pv_temp;   /* Stick new record as last one. */
  596.         pv_tail = pv_tail -> next;    /* And continue to last record. */
  597.     }
  598.     }
  599.     pv_tail -> next = NULL;
  600.  
  601.     return p_vrtx;
  602. }
  603.  
  604. /*
  605.  * Combines N vertices in pair to form N-1 edges.
  606.  * Returns pointer to the edge list (pe_tail will point on last edge in list).
  607.  */
  608. static struct edge_struct *gen_edges(grid_x_max, p_vrtx, pe_tail)
  609. int grid_x_max;
  610. struct vrtx_struct *p_vrtx;
  611. struct edge_struct **pe_tail;
  612. {
  613.     int i;
  614.     struct edge_struct *p_edge, *pe_temp;
  615.  
  616.     for (i=0; i<grid_x_max-1; i++) {         /* Generate grid_x_max-1 edges: */
  617.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  618.                         "contour edge");
  619.     pe_temp -> vertex[0] = p_vrtx;              /* First vertex of edge. */
  620.     p_vrtx = p_vrtx -> next;                     /* Skip to next vertex. */
  621.     pe_temp -> vertex[1] = p_vrtx;             /* Second vertex of edge. */
  622.         if (i == 0)                                    /* First edge in row: */
  623.         p_edge = (*pe_tail) = pe_temp;
  624.     else {
  625.         (*pe_tail) -> next = pe_temp;   /* Stick new record as last one. */
  626.         *pe_tail = (*pe_tail) -> next;   /* And continue to last record. */
  627.      }
  628.     }
  629.     (*pe_tail) -> next = NULL;
  630.  
  631.     return p_edge;
  632. }
  633.  
  634. /*
  635.  * Combines 2 lists of N vertices each into edge list:
  636.  * The dots (.) are the vertices list, and the              .  .  .  .
  637.  *  edges generated are alternations of vertical edges      |\ |\ |\ |
  638.  *  (|) and diagonal ones (\).                              | \| \| \|
  639.  *  A pointer to edge list (alternate | , \) is returned    .  .  .  .
  640.  * Note this list will have (2*grid_x_max-1) edges (pe_tail points on last
  641.  * record).
  642.  */
  643. static struct edge_struct *gen_edges_middle(grid_x_max, p_vrtx1, p_vrtx2,
  644.                                 pe_tail)
  645. int grid_x_max;
  646. struct vrtx_struct *p_vrtx1, *p_vrtx2;
  647. struct edge_struct **pe_tail;
  648. {
  649.     int i;
  650.     struct edge_struct *p_edge, *pe_temp;
  651.  
  652.     /* Gen first (|). */
  653.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  654.                             "contour edge");
  655.     pe_temp -> vertex[0] = p_vrtx2;                 /* First vertex of edge. */
  656.     pe_temp -> vertex[1] = p_vrtx1;                /* Second vertex of edge. */
  657.     p_edge = (*pe_tail) = pe_temp;
  658.  
  659.     /* Advance in vrtx list grid_x_max-1 times, and gen. 2 edges /| for each.*/
  660.     for (i=0; i<grid_x_max-1; i++) {
  661.     /* The / edge. */
  662.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  663.                             "contour edge");
  664.     pe_temp -> vertex[0] = p_vrtx1;             /* First vertex of edge. */
  665.     pe_temp -> vertex[1] = p_vrtx2 -> next;    /* Second vertex of edge. */
  666.         (*pe_tail) -> next = pe_temp;       /* Stick new record as last one. */
  667.     *pe_tail = (*pe_tail) -> next;       /* And continue to last record. */
  668.  
  669.     /* The | edge. */
  670.     pe_temp = (struct edge_struct *) alloc((unsigned long)sizeof(struct edge_struct),
  671.                             "contour edge");
  672.     pe_temp -> vertex[0] = p_vrtx2 -> next;     /* First vertex of edge. */
  673.     pe_temp -> vertex[1] = p_vrtx1 -> next;    /* Second vertex of edge. */
  674.         (*pe_tail) -> next = pe_temp;       /* Stick new record as last one. */
  675.     *pe_tail = (*pe_tail) -> next;       /* And continue to last record. */
  676.  
  677.         p_vrtx1 = p_vrtx1 -> next;   /* Skip to next vertices in both lists. */
  678.         p_vrtx2 = p_vrtx2 -> next;
  679.     }
  680.     (*pe_tail) -> next = NULL;
  681.  
  682.     return p_edge;
  683. }
  684.  
  685. /*
  686.  * Combines 3 lists of edges into triangles:
  687.  * 1. p_edge1: Top horizontal edge list:        -----------------------
  688.  * 2. p_edge_middge: middle edge list:         |\  |\  |\  |\  |\  |\  |
  689.  *                                             |  \|  \|  \|  \|  \|  \|
  690.  * 3. p_edge2: Bottom horizontal edge list:     -----------------------
  691.  * Note that p_edge1/2 lists has grid_x_max-1 edges, while p_edge_middle has
  692.  * (2*grid_x_max-1) edges.
  693.  * The routine simple scans the two list    Upper 1         Lower
  694.  * and generate two triangle upper one        ----         | \
  695.  * and lower one from the lists:             0\   |2      0|   \1
  696.  * (Nums. are edges order in polys)             \ |         ----
  697.  * The routine returns a pointer to a                         2
  698.  * polygon list (pp_tail points on last polygon).          1
  699.  *                                                   -----------
  700.  * In addition, the edge lists are updated -        | \   0     |
  701.  * each edge has two pointers on the two            |   \       |
  702.  * (one active if boundary) polygons which         0|1   0\1   0|1
  703.  * uses it. These two pointer to polygons           |       \   |
  704.  * are named: poly[0], poly[1]. The diagram         |    1    \ |
  705.  * on the right show how they are used for the       -----------
  706.  * upper and lower polygons.                             0
  707.  */
  708. static struct poly_struct *gen_polys(grid_x_max, p_edge1, p_edge_middle,
  709.                             p_edge2, pp_tail)
  710. int grid_x_max;
  711. struct edge_struct *p_edge1, *p_edge_middle, *p_edge2;
  712. struct poly_struct **pp_tail;
  713. {
  714.     int i;
  715.     struct poly_struct *p_poly, *pp_temp;
  716.  
  717.     p_edge_middle -> poly[0] = NULL;                /* Its boundary! */
  718.  
  719.     /* Advance in vrtx list grid_x_max-1 times, and gen. 2 polys for each. */
  720.     for (i=0; i<grid_x_max-1; i++) {
  721.     /* The Upper. */
  722.     pp_temp = (struct poly_struct *) alloc((unsigned long)sizeof(struct poly_struct),
  723.                             "contour poly");
  724.     /* Now update polys about its edges, and edges about the polygon. */
  725.     pp_temp -> edge[0] = p_edge_middle -> next;
  726.     p_edge_middle -> next -> poly[1] = pp_temp;
  727.     pp_temp -> edge[1] = p_edge1;
  728.     p_edge1 -> poly[0] = pp_temp;
  729.     pp_temp -> edge[2] = p_edge_middle -> next -> next;
  730.     p_edge_middle -> next -> next -> poly[0] = pp_temp;
  731.     if (i == 0)                   /* Its first one in list: */
  732.         p_poly = (*pp_tail) = pp_temp;
  733.     else {
  734.         (*pp_tail) -> next = pp_temp;
  735.         *pp_tail = (*pp_tail) -> next;
  736.     }
  737.  
  738.     /* The Lower. */
  739.     pp_temp = (struct poly_struct *) alloc((unsigned long)sizeof(struct poly_struct),
  740.                             "contour poly");
  741.     /* Now update polys about its edges, and edges about the polygon. */
  742.     pp_temp -> edge[0] = p_edge_middle;
  743.     p_edge_middle -> poly[1] = pp_temp;
  744.     pp_temp -> edge[1] = p_edge_middle -> next;
  745.     p_edge_middle -> next -> poly[0] = pp_temp;
  746.     pp_temp -> edge[2] = p_edge2;
  747.     p_edge2 -> poly[1] = pp_temp;
  748.     (*pp_tail) -> next = pp_temp;
  749.     *pp_tail = (*pp_tail) -> next;
  750.  
  751.         p_edge1 = p_edge1 -> next;
  752.         p_edge2 = p_edge2 -> next;
  753.         p_edge_middle = p_edge_middle -> next -> next;
  754.     }
  755.     p_edge_middle -> poly[1] = NULL;                /* Its boundary! */
  756.     (*pp_tail) -> next = NULL;
  757.  
  758.     return p_poly;
  759. }
  760.  
  761. /*
  762.  * Calls the (hopefully) desired interpolation/approximation routine.
  763.  */
  764. static void put_contour(p_cntr, z_level, x_min, x_max, y_min, y_max, contr_kind)
  765. struct cntr_struct *p_cntr;
  766. double z_level, x_min, x_max, y_min, y_max;
  767. int contr_kind;
  768. {
  769.     if (!p_cntr) return;            /* Nothing to do if it is empty contour. */
  770.  
  771.     switch (interp_kind) {
  772.     case INTERP_NOTHING:              /* No interpolation/approximation. */
  773.         put_contour_nothing(p_cntr);
  774.         break;
  775.     case INTERP_CUBIC:                    /* Cubic spline interpolation. */
  776.         put_contour_cubic(p_cntr, z_level, x_min, x_max, y_min, y_max,
  777.                                 contr_kind);
  778.         break;
  779.     case APPROX_BSPLINE:                       /* Bspline approximation. */
  780.         put_contour_bspline(p_cntr, z_level, x_min, x_max, y_min, y_max,
  781.                                     contr_kind);
  782.         break;
  783.     }
  784.  
  785.     free_contour(p_cntr);
  786. }
  787.  
  788. /*
  789.  * Simply puts contour coordinates in order with no interpolation or
  790.  * approximation.
  791.  */
  792. static put_contour_nothing(p_cntr)
  793. struct cntr_struct *p_cntr;
  794. {
  795.     while (p_cntr) {
  796.     add_cntr_point(p_cntr -> X, p_cntr -> Y);
  797.     p_cntr = p_cntr -> next;
  798.     }
  799.     end_crnt_cntr();
  800. }
  801.  
  802. /*
  803.  * Find Complete Cubic Spline Interpolation.
  804.  */
  805. static put_contour_cubic(p_cntr, z_level, x_min, x_max, y_min, y_max,
  806.                                  contr_kind)
  807. struct cntr_struct *p_cntr;
  808. double z_level, x_min, x_max, y_min, y_max;
  809. int contr_kind;
  810. {
  811.     int num_pts, i;
  812.     double tx1, ty1, tx2, ty2;                    /* Tangents at end points. */
  813.     struct cntr_struct *pc_temp;
  814.  
  815.     num_pts = count_contour(p_cntr);         /* Number of points in contour. */
  816.  
  817.     if (num_pts > 2) {  /* Take into account 3 points in tangent estimation. */
  818.     calc_tangent(3, p_cntr -> X, p_cntr -> next -> X,
  819.             p_cntr -> next -> next -> X,
  820.             p_cntr -> Y, p_cntr -> next -> Y,
  821.             p_cntr -> next -> next -> Y, &tx1, &ty1);
  822.     pc_temp = p_cntr;
  823.     for (i=3; i<num_pts; i++) pc_temp = pc_temp -> next;/* Go to the end.*/
  824.     calc_tangent(3, pc_temp -> next -> next -> X,
  825.              pc_temp -> next -> X, pc_temp -> X,
  826.             pc_temp -> next -> next -> Y,
  827.             pc_temp -> next -> Y, pc_temp -> Y, &tx2, &ty2);
  828.         tx2 = (-tx2);   /* Inverse the vector as we need opposite direction. */
  829.         ty2 = (-ty2);
  830.     }
  831.     /* If following (num_pts > 1) is TRUE then exactly 2 points in contour.  */
  832.     else if (num_pts > 1) {/* Take into account 2 points in tangent estimat. */
  833.     calc_tangent(2, p_cntr -> X, p_cntr -> next -> X, 0.0,
  834.             p_cntr -> Y, p_cntr -> next -> Y, 0.0, &tx1, &ty1);
  835.     calc_tangent(2, p_cntr -> next -> X, p_cntr -> X, 0.0,
  836.             p_cntr -> next -> Y, p_cntr -> Y, 0.0, &tx2, &ty2);
  837.         tx2 = (-tx2);   /* Inverse the vector as we need opposite direction. */
  838.         ty2 = (-ty2);
  839.     }
  840.     else return(0);            /* Only one point (???) - ignore it. */
  841.  
  842.     switch (contr_kind) {
  843.     case OPEN_CONTOUR:
  844.         break;
  845.     case CLOSED_CONTOUR:
  846.         tx1 = tx2 = (tx1 + tx2) / 2.0;         /* Make tangents equal. */
  847.         ty1 = ty2 = (ty1 + ty2) / 2.0;
  848.         break;
  849.     }
  850.     complete_spline_interp(p_cntr, num_pts, 0.0, 1.0, tx1, ty1, tx2, ty2);
  851.     end_crnt_cntr();
  852. }
  853.  
  854. /*
  855.  * Find Bspline approximation for this data set.
  856.  * Uses global variable num_approx_pts to determine number of samples per
  857.  * interval, where the knot vector intervals are assumed to be uniform, and
  858.  * Global variable bspline_order for the order of Bspline to use.
  859.  */
  860. static put_contour_bspline(p_cntr, z_level, x_min, x_max, y_min, y_max,
  861.                                 contr_kind)
  862. struct cntr_struct *p_cntr;
  863. double z_level, x_min, x_max,  y_min, y_max;
  864. int contr_kind;
  865. {
  866.     int num_pts, order = bspline_order;
  867.  
  868.     num_pts = count_contour(p_cntr);         /* Number of points in contour. */
  869.     if (num_pts < 2) return(0);     /* Can't do nothing if empty or one points! */
  870.     /* Order must be less than number of points in curve - fix it if needed. */
  871.     if (order > num_pts - 1) order = num_pts - 1;
  872.  
  873.     gen_bspline_approx(p_cntr, num_pts, order, contr_kind);
  874.     end_crnt_cntr();
  875. }
  876.  
  877. /*
  878.  * Estimate the tangents according to the n last points where n might be
  879.  * 2 or 3 (if 2 onlt x1, x2).
  880.  */
  881. static calc_tangent(n, x1, x2, x3, y1, y2, y3, tx, ty)
  882. int n;
  883. double x1, x2, x3, y1, y2, y3, *tx, *ty;
  884. {
  885.     double v1[2], v2[2], v1_magnitude, v2_magnitude;
  886.  
  887.     switch (n) {
  888.     case 2:
  889.         *tx = (x2 - x1) * 0.3;
  890.         *ty = (y2 - y1) * 0.3;
  891.         break;
  892.     case 3:
  893.         v1[0] = x2 - x1;   v1[1] = y2 - y1;
  894.         v2[0] = x3 - x2;   v2[1] = y3 - y2;
  895.         v1_magnitude = sqrt(sqr(v1[0]) + sqr(v1[1]));
  896.         v2_magnitude = sqrt(sqr(v2[0]) + sqr(v2[1]));
  897.         *tx = (v1[0] / v1_magnitude) - (v2[0] / v2_magnitude) * 0.1;
  898.         *tx *= v1_magnitude * 0.1;  /* Make tangent less than magnitude. */
  899.         *ty = (v1[1] / v1_magnitude) - (v2[1] / v2_magnitude) * 0.1;
  900.         *ty *= v1_magnitude * 0.1;  /* Make tangent less than magnitude. */
  901.         break;
  902.     default:                       /* Should not happen! */
  903.         (*ty) = 0.1;
  904.         *tx = 0.1;
  905.         break;
  906.     }
  907. }
  908.  
  909. /*
  910.  * Free all elements in the contour list.
  911.  */
  912. static void free_contour(p_cntr)
  913. struct cntr_struct *p_cntr;
  914. {
  915.     struct cntr_struct *pc_temp;
  916.  
  917.     while (p_cntr) {
  918.     pc_temp = p_cntr;
  919.     p_cntr = p_cntr -> next;
  920.     free((char *) pc_temp);
  921.     }
  922. }
  923.  
  924. /*
  925.  * Counts number of points in contour.
  926.  */
  927. static int count_contour(p_cntr)
  928. struct cntr_struct *p_cntr;
  929. {
  930.     int count = 0;
  931.  
  932.     while (p_cntr) {
  933.     count++;
  934.     p_cntr = p_cntr -> next;
  935.     }
  936.     return count;
  937. }
  938.  
  939. /*
  940.  * Interpolate given point list (defined via p_cntr) using Complete
  941.  * Spline interpolation.
  942.  */
  943. static complete_spline_interp(p_cntr, n, t_min, t_max, tx1, ty1, tx2, ty2)
  944. struct cntr_struct *p_cntr;
  945. int n;
  946. double t_min, t_max, tx1, ty1, tx2, ty2;
  947. {
  948.     double dt, *tangents_x, *tangents_y;
  949.     int i;
  950.  
  951.     tangents_x = (double *) alloc((unsigned long) (sizeof(double) * n),
  952.                         "contour c_s_intr");
  953.     tangents_y = (double *) alloc((unsigned long) (sizeof(double) * n),
  954.                         "contour c_s_intr");
  955.  
  956.     if (n > 1) prepare_spline_interp(tangents_x, tangents_y, p_cntr, n,
  957.                     t_min, t_max, tx1, ty1, tx2, ty2);
  958.     else {
  959.     free((char *) tangents_x);
  960.     free((char *) tangents_y);
  961.     return(0);
  962.     }
  963.  
  964.     dt = (t_max-t_min)/(n-1);
  965.  
  966.     add_cntr_point(p_cntr -> X, p_cntr -> Y);           /* First point. */
  967.  
  968.     for (i=0; i<n-1; i++) {
  969.         hermit_interp(p_cntr -> X, p_cntr -> Y,
  970.                      tangents_x[i], tangents_y[i],
  971.              p_cntr -> next -> X, p_cntr -> next -> Y,
  972.                      tangents_x[i+1], tangents_y[i+1], dt);
  973.  
  974.         p_cntr = p_cntr -> next;
  975.     }
  976.  
  977.     free((char *) tangents_x);
  978.     free((char *) tangents_y);
  979. }
  980.  
  981. /*
  982.  * Routine to calculate intermidiate value of the Hermit Blending function:
  983.  * This routine should be called only ONCE at the beginning of the program.
  984.  */
  985. static calc_hermit_table()
  986. {
  987.     int i;
  988.     double t, dt;
  989.  
  990.     hermit_table = (table_entry *) alloc ((unsigned long) (sizeof(table_entry) *
  991.                         (num_approx_pts + 1)),
  992.                         "contour hermit table");
  993.     t = 0;
  994.     dt = 1.0/num_approx_pts;
  995.     for (i=0; i<=num_approx_pts; i++) {
  996.         hermit_table[i][0] = (t-1)*(t-1)*(2*t+1);             /* h00. */
  997.         hermit_table[i][1] = t*t*(-2*t+3);                 /* h10. */
  998.         hermit_table[i][2] = t*(t-1)*(t-1);                 /* h01. */
  999.         hermit_table[i][3] = t*t*(t-1);                     /* h11. */
  1000.         t = t + dt;
  1001.     }
  1002. }
  1003.  
  1004. /*
  1005.  * Routine to generate an hermit interpolation between two points given as
  1006.  * two InterpStruct structures. Assume hermit_table is already calculated.
  1007.  * Currently the points generated are printed to stdout as two reals (X, Y).
  1008.  */
  1009. static hermit_interp(x1, y1, tx1, ty1, x2, y2, tx2, ty2, dt)
  1010. double x1, y1, tx1, ty1, x2, y2, tx2, ty2, dt;
  1011. {
  1012.     int i;
  1013.     double x, y, vec_size, tang_size;
  1014.  
  1015.     tx1 *= dt;  ty1 *= dt; /* Normalize the tangents according to param. t.  */
  1016.     tx2 *= dt;  ty2 *= dt;
  1017.  
  1018.     /* Normalize the tangents so that their magnitude will be 1/3 of the     */
  1019.     /* segment length. This tumb rule guaranteed no cusps or loops!          */
  1020.     /* Note that this normalization keeps continuity to be G1 (but not C1).  */
  1021.     vec_size = sqrt(sqr(x1 - x2) + sqr(y2 - y1));
  1022.     tang_size = sqrt(sqr(tx1) + sqr(ty1));                  /* Normalize T1. */
  1023.     if (tang_size * 3 > vec_size) {
  1024.     tx1 *= vec_size / (tang_size * 3);
  1025.     ty1 *= vec_size / (tang_size * 3);
  1026.     }
  1027.     tang_size = sqrt(sqr(tx2) + sqr(ty2));                  /* Normalize T2. */
  1028.     if (tang_size * 3 > vec_size) {
  1029.     tx2 *= vec_size / (tang_size * 3);
  1030.     ty2 *= vec_size / (tang_size * 3);
  1031.     }
  1032.  
  1033.     for (i=1; i<=num_approx_pts; i++) {      /* Note we start from 1 - first */
  1034.         x = hermit_table[i][0] * x1 +       /* point is not printed as it is */
  1035.             hermit_table[i][1] * x2 +   /* redundent (last on last section). */
  1036.             hermit_table[i][2] * tx1 +
  1037.             hermit_table[i][3] * tx2;
  1038.         y = hermit_table[i][0] * y1 +
  1039.             hermit_table[i][1] * y2 +
  1040.             hermit_table[i][2] * ty1 +
  1041.             hermit_table[i][3] * ty2;
  1042.     add_cntr_point(x, y);
  1043.     }
  1044. }
  1045.  
  1046. /*
  1047.  * Routine to Set up the 3*N mat for solve_tri_diag routine used in the
  1048.  * Complete Spline Interpolation. Returns TRUE of calc O.K.
  1049.  * Gets the points list in p_cntr (Of length n) and with tangent vectors tx1,
  1050.  * ty1 at starting point and tx2, ty2 and end point.
  1051.  */
  1052. static prepare_spline_interp(tangents_x, tangents_y, p_cntr, n, t_min, t_max,
  1053.                tx1, ty1, tx2, ty2)
  1054. double tangents_x[], tangents_y[];
  1055. struct cntr_struct *p_cntr;
  1056. int n;
  1057. double t_min, t_max, tx1, ty1, tx2, ty2;
  1058. {
  1059.     int i;
  1060.     double *r, t, dt;
  1061.     tri_diag *m;           /* The tri-diagonal matrix is saved here. */
  1062.     struct cntr_struct *p;
  1063.  
  1064.     m = (tri_diag *) alloc((unsigned long) (sizeof(tri_diag) * n),
  1065.                         "contour tri_diag");
  1066.     r = (double *) alloc((unsigned long) (sizeof(double) * n),
  1067.                         "contour tri_diag2");
  1068.     n--;
  1069.  
  1070.     p = p_cntr;
  1071.     m[0][0] = 0.0;    m[0][1] = 1.0;    m[0][2] = 0.0;
  1072.     m[n][0] = 0.0;    m[n][1] = 1.0;    m[n][2] = 0.0;
  1073.     r[0] = tx1;                           /* Set start tangent. */
  1074.     r[n] = tx2;                         /* Set end tangent. */
  1075.     t = t_min;
  1076.     dt = (t_max-t_min)/n;
  1077.     for (i=1; i<n; i++) {
  1078.        t = t + dt;
  1079.        m[i][0] = dt;
  1080.        m[i][2] = dt;
  1081.        m[i][1] = 2 * (m[i][0] + m[i][2]);
  1082.        r[i] = m[i][0] * ((p -> next -> X) - (p -> X)) / m[i][2]
  1083.             + m[i][2] * ((p -> next -> next -> X) - 
  1084.                          (p -> next -> X)) / m[i][0];
  1085.        r[i] *= 3.0;
  1086.        p = p -> next;
  1087.     }
  1088.  
  1089.     if (!solve_tri_diag(m, r, tangents_x, n+1)) { /* Find the X(t) tangents. */
  1090.         free((char *) m);
  1091.         free((char *) r);
  1092.     int_error("Cannt interpolate X using complete splines", NO_CARET);
  1093.     }
  1094.  
  1095.     p = p_cntr;
  1096.     m[0][0] = 0.0;    m[0][1] = 1.0;    m[0][2] = 0.0;
  1097.     m[n][0] = 0.0;    m[n][1] = 1.0;    m[n][2] = 0.0;
  1098.     r[0] = ty1;                           /* Set start tangent. */
  1099.     r[n] = ty2;                         /* Set end tangent. */
  1100.     t = t_min;
  1101.     dt = (t_max-t_min)/n;
  1102.     for (i=1; i<n; i++) {
  1103.        t = t + dt;
  1104.        m[i][0] = dt;
  1105.        m[i][2] = dt;
  1106.        m[i][1] = 2 * (m[i][0] + m[i][2]);
  1107.        r[i] = m[i][0] * ((p -> next -> Y) - (p -> Y)) / m[i][2]
  1108.             + m[i][2] * ((p -> next -> next -> Y) -
  1109.                          (p -> next -> Y)) / m[i][0];
  1110.        r[i] *= 3.0;
  1111.        p = p -> next;
  1112.     }
  1113.  
  1114.     if (!solve_tri_diag(m, r, tangents_y, n+1)) { /* Find the Y(t) tangents. */
  1115.         free((char *) m);
  1116.         free((char *) r);
  1117.     int_error("Cannt interpolate Y using complete splines", NO_CARET);
  1118.     }
  1119.     free((char *) m);
  1120.     free((char *) r);
  1121. }
  1122.  
  1123. /*
  1124.  * Solve tri diagonal linear system equation. The tri diagonal matrix is
  1125.  * defined via matrix M, right side is r, and solution X i.e. M * X = R.
  1126.  * Size of system given in n. Return TRUE if solution exist.
  1127.  */
  1128. static int solve_tri_diag(m, r, x, n)
  1129. tri_diag m[];
  1130. double r[], x[];
  1131. int n;
  1132. {
  1133.     int i;
  1134.     double t;
  1135.  
  1136.     for (i=1; i<n; i++) {   /* Eliminate element m[i][i-1] (lower diagonal). */
  1137.     if (m[i-1][1] == 0) return FALSE;
  1138.     t = m[i][0] / m[i-1][1];        /* Find ratio between the two lines. */
  1139.     m[i][0] = m[i][0] - m[i-1][1] * t;
  1140.     m[i][1] = m[i][1] - m[i-1][2] * t;
  1141.     r[i] = r[i] - r[i-1] * t;
  1142.     }
  1143.     /* Now do back subtitution - update the solution vector X: */
  1144.     if (m[n-1][1] == 0) return FALSE;
  1145.     x[n-1] = r[n-1] / m[n-1][1];               /* Find last element. */
  1146.     for (i=n-2; i>=0; i--) {
  1147.     if (m[i][1] == 0) return FALSE;
  1148.     x[i] = (r[i] - x[i+1] * m[i][2]) / m[i][1];
  1149.     }
  1150.     return TRUE;
  1151. }
  1152.  
  1153. /*
  1154.  * Generate a Bspline curve defined by all the points given in linked list p:
  1155.  * Algorithm: using deBoor algorithm
  1156.  * Note: if Curvekind is OPEN_CONTOUR than Open end knot vector is assumed,
  1157.  *       else (CLOSED_CONTOUR) Float end knot vector is assumed.
  1158.  * It is assumed that num_of_points is at list 2, and order of Bspline is less
  1159.  * than num_of_points!
  1160.  */
  1161. static gen_bspline_approx(p_cntr, num_of_points, order, contour_kind)
  1162. struct cntr_struct *p_cntr;
  1163. int num_of_points, order, contour_kind;
  1164. {
  1165.     int i, knot_index = 0, pts_count = 1;
  1166.     double dt, t, next_t, t_min, t_max, x, y;
  1167.     struct cntr_struct *pc_temp = p_cntr, *pc_tail;
  1168.  
  1169.     /* If the contour is Closed one we must update few things:               */
  1170.     /* 1. Make the list temporary circular, so we can close the contour.     */
  1171.     /* 2. Update num_of_points - increase it by "order-1" so contour will be */
  1172.     /*    closed. This will evaluate order more sections to close it!        */
  1173.     if (contour_kind == CLOSED_CONTOUR) {
  1174.     pc_tail = p_cntr;
  1175.     while (pc_tail -> next) pc_tail = pc_tail -> next;/* Find last point.*/
  1176.     pc_tail -> next = p_cntr;   /* Close contour list - make it circular.*/
  1177.     num_of_points += order;
  1178.     }
  1179.  
  1180.     /* Find first (t_min) and last (t_max) t value to eval: */
  1181.     t = t_min = fetch_knot(contour_kind, num_of_points, order, order);
  1182.     t_max = fetch_knot(contour_kind, num_of_points, order, num_of_points);
  1183.     next_t = t_min + 1.0;
  1184.     knot_index = order;
  1185.     dt = 1.0/num_approx_pts;            /* Number of points per one section. */
  1186.  
  1187.  
  1188.     while (t<t_max) {
  1189.     if (t > next_t) {
  1190.         pc_temp = pc_temp -> next;     /* Next order ctrl. pt. to blend. */
  1191.             knot_index++;
  1192.         next_t += 1.0;
  1193.     }
  1194.         eval_bspline(t, pc_temp, num_of_points, order, knot_index,
  1195.                         contour_kind, &x, &y);   /* Next pt. */
  1196.     add_cntr_point(x, y);
  1197.     pts_count++;
  1198.     /* As we might have some real number round off problems we must      */
  1199.     /* test if we dont produce too many points here...                   */
  1200.     if (pts_count + 1 == num_approx_pts * (num_of_points - order) + 1)
  1201.             break;
  1202.         t += dt;
  1203.     }
  1204.  
  1205.     eval_bspline(t_max - EPSILON, pc_temp, num_of_points, order, knot_index,
  1206.         contour_kind, &x, &y);
  1207.     /* If from round off errors we need more than one last point: */
  1208.     for (i=pts_count; i<num_approx_pts * (num_of_points - order) + 1; i++)
  1209.     add_cntr_point(x, y);                /* Complete the contour. */
  1210.  
  1211.     if (contour_kind == CLOSED_CONTOUR)     /* Update list - un-circular it. */
  1212.     pc_tail -> next = NULL;
  1213. }
  1214.  
  1215. /*
  1216.  * The recursive routine to evaluate the B-spline value at point t using
  1217.  * knot vector PKList, and the control points Pdtemp. Returns x, y after the
  1218.  * division by the weight w. Note that Pdtemp points on the first control
  1219.  * point to blend with. The B-spline is of order order.
  1220.  */
  1221. static eval_bspline(t, p_cntr, num_of_points, order, j, contour_kind, x, y)
  1222. double t;
  1223. struct cntr_struct *p_cntr;
  1224. int num_of_points, order, j, contour_kind;
  1225. double *x, *y;
  1226. {
  1227.     int i, p;
  1228.     double ti, tikp, *dx, *dy;      /* Copy p_cntr into it to make it faster. */
  1229.  
  1230.     dx = (double *) alloc((unsigned long) (sizeof(double) * (order + j)),
  1231.                         "contour b_spline");
  1232.     dy = (double *) alloc((unsigned long) (sizeof(double) * (order + j)),
  1233.                         "contour b_spline");
  1234.     /* Set the dx/dy - [0] iteration step, control points (p==0 iterat.): */
  1235.     for (i=j-order; i<=j; i++) {
  1236.         dx[i] = p_cntr -> X;
  1237.         dy[i] = p_cntr -> Y;
  1238.         p_cntr = p_cntr -> next;
  1239.     }
  1240.  
  1241.     for (p=1; p<=order; p++) {        /* Iteration (b-spline level) counter. */
  1242.     for (i=j; i>=j-order+p; i--) {           /* Control points indexing. */
  1243.             ti = fetch_knot(contour_kind, num_of_points, order, i);
  1244.             tikp = fetch_knot(contour_kind, num_of_points, order, i+order+1-p);
  1245.         if (ti == tikp) {   /* Should not be a problems but how knows... */
  1246.         }
  1247.         else {
  1248.         dx[i] = dx[i] * (t - ti)/(tikp-ti) +         /* Calculate x. */
  1249.             dx[i-1] * (tikp-t)/(tikp-ti);
  1250.         dy[i] = dy[i] * (t - ti)/(tikp-ti) +         /* Calculate y. */
  1251.             dy[i-1] * (tikp-t)/(tikp-ti);
  1252.         }
  1253.     }
  1254.     }
  1255.     *x = dx[j]; *y = dy[j];
  1256.     free((char *) dx);
  1257.     free((char *) dy);
  1258. }
  1259.  
  1260. /*
  1261.  * Routine to get the i knot from uniform knot vector. The knot vector
  1262.  * might be float (Knot(i) = i) or open (where the first and last "order"
  1263.  * knots are equal). contour_kind determines knot kind - OPEN_CONTOUR means
  1264.  * open knot vector, and CLOSED_CONTOUR selects float knot vector.
  1265.  * Note the knot vector is not exist and this routine simulates it existance
  1266.  * Also note the indexes for the knot vector starts from 0.
  1267.  */
  1268. static double fetch_knot(contour_kind, num_of_points, order, i)
  1269. int contour_kind, num_of_points, order, i;
  1270. {
  1271.     switch (contour_kind) {
  1272.     case OPEN_CONTOUR:
  1273.         if (i <= order) return 0.0;
  1274.         else if (i <= num_of_points) return (double) (i - order);
  1275.          else return (double) (num_of_points - order);
  1276.     case CLOSED_CONTOUR:
  1277.         return (double) i;
  1278.     default: /* Should never happen */
  1279.         return 1.0;
  1280.     }
  1281. #ifdef sequent
  1282.     return 1.0;
  1283. #endif
  1284. }
  1285.